package com.hongye.proprietary.exception;

import com.hongye.common.exception.BizCodeEnum;
import com.hongye.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author lins
 * @date 2021/10/15 14:37
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.hongye.house.controller")
public class HongYeExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.info("数据校验出现异常:{},异常类型:{}",e.getMessage(),e.getClass());
        HashMap<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(item->{
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data", map);
    }
    @ExceptionHandler(value = NullPointerException.class)
    public R handleValidException(NullPointerException e){
        log.info("空指针异常:{},异常类型:{}",e.getMessage(),e.getClass());
        HashMap<String, String> map = new HashMap<>();
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            String className = stackTraceElement.getClassName();
            map.put("className", className);
            String methodName = stackTraceElement.getMethodName();
            map.put("methodName", methodName);
            String fileName = stackTraceElement.getFileName();
            map.put("fileName", fileName);
            String s = stackTraceElement.toString();
            map.put("s", s);
        }
        String message = e.getMessage();
        map.put("message", message);
        return R.error(BizCodeEnum.NULL_EXCEPTION.getCode(), BizCodeEnum.NULL_EXCEPTION.getMessage()).put("data", map);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.info("程序出现异常:{},异常类型:{}",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.HONGYE_UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
